var util = require('../../utils/util.js');
const Upyun = require('../../utils/upyun-wxapp-sdk');
var app = getApp();
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
});

let sysInfo = tt.getSystemInfoSync();
let SCREEN_WIDTH = sysInfo.screenWidth
let PAGE_X, // 手按下的x位置
  PAGE_Y, // 手按下y的位置 
  PR = sysInfo.pixelRatio, // dpi
  T_PAGE_X, // 手移动的时候x的位置
  T_PAGE_Y, // 手移动的时候Y的位置
  CUT_L, // 初始化拖拽元素的left值
  CUT_T, // 初始化拖拽元素的top值
  CUT_R, // 初始化拖拽元素的
  CUT_B, // 初始化拖拽元素的
  CUT_W, // 初始化拖拽元素的宽度
  CUT_H, //  初始化拖拽元素的高度
  IMG_RATIO, // 图片比例
  IMG_REAL_W, // 图片实际的宽度
  IMG_REAL_H, // 图片实际的高度
  IMG_REAL_SHOW_W, // 图片实际显示的宽度
  IMG_REAL_SHOW_H, // 图片实际显示的高度
  DRAFG_MOVE_RATIO = 1, //移动时候的比例,
  INIT_DRAG_POSITION = 100, // 初始化屏幕宽度和裁剪区域的宽度之差，用于设置初始化裁剪的宽度
  DRAW_IMAGE_W = sysInfo.screenWidth // 设置生成的图片宽度


Page({
  /**
   * 页面的初始数据
   */
  data: {

    imageSrc: '',
    imageName: '',
    isShowImg: false,
    // 初始化的宽高
    cropperInitW: SCREEN_WIDTH,
    cropperInitH: SCREEN_WIDTH,
    // 动态的宽高
    cropperW: SCREEN_WIDTH,
    cropperH: SCREEN_WIDTH,
    // 动态的left top值
    cropperL: 0,
    cropperT: 0,

    transL: 0,
    transT: 0,

    // 图片缩放值
    scaleP: 0,
    imageW: 0,
    imageH: 0,

    // 裁剪框 宽高
    cutL: 0,
    cutT: 0,
    cutB: SCREEN_WIDTH,
    cutR: '100%',
    qualityWidth: DRAW_IMAGE_W,
    innerAspectRadio: DRAFG_MOVE_RATIO

  },

  cuid: '',

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    tt.setNavigationBarTitle({
      title: "選擇頭像"
    })

    var that = this
    app.LoginUserInfo(function(res){
      if(res && res != '-1' && res != '-2'){
        that.cuid = res.uid
      }
    })

    let avatarLink = options.avatar
    if (avatarLink.indexOf('/images/') == 0) {
      avatarLink = '../..' + options.avatar
    }
    this.setData({
      imageSrc: avatarLink
    })
    console.log("原头像url:" + this.data.imageSrc)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

    this.loadImage();

  },


  getImage: function () {
    var _this = this
    tt.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        console.log("本地图片信息：", res);
        const tempFiles = res.tempFiles;
        console.log("APP端：", res)
        _this.setData({
          imageSrc: tempFiles[0].tempFilePath
        })
        _this.loadImage();
      },

      fail: function ({
        errMsg
      }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  loadImage: function () {
    var _this = this
    tt.showLoading({
      title: '图片加载中...',
    })
    console.log('图片加载链接：', _this.data.imageSrc)
    tt.getImageInfo({
      src: _this.data.imageSrc,
      success: function success(res) {
        IMG_REAL_W = res.width
        IMG_REAL_H = res.height
        IMG_RATIO = res.width / res.height
        if (IMG_RATIO >= 1) {
          IMG_REAL_SHOW_W = SCREEN_WIDTH
          IMG_REAL_SHOW_H = SCREEN_WIDTH / IMG_RATIO
        } else {
          IMG_REAL_SHOW_W = SCREEN_WIDTH * IMG_RATIO
          IMG_REAL_SHOW_H = SCREEN_WIDTH
        }
        let minRange = IMG_REAL_SHOW_W > IMG_REAL_SHOW_H ? IMG_REAL_SHOW_W : IMG_REAL_SHOW_H
        INIT_DRAG_POSITION = minRange > INIT_DRAG_POSITION ? INIT_DRAG_POSITION : minRange
        // 根据图片的宽高显示不同的效果   保证图片可以正常显示
        if (IMG_RATIO >= 1) {
          let cutT = Math.ceil((SCREEN_WIDTH / IMG_RATIO - (SCREEN_WIDTH / IMG_RATIO -
            INIT_DRAG_POSITION)) / 2);
          let cutB = cutT;
          let cutL = Math.ceil((SCREEN_WIDTH - SCREEN_WIDTH + INIT_DRAG_POSITION) / 2);
          let cutR = cutL;
          _this.setData({
            cropperW: SCREEN_WIDTH,
            cropperH: SCREEN_WIDTH / IMG_RATIO,
            // 初始化left right
            cropperL: Math.ceil((SCREEN_WIDTH - SCREEN_WIDTH) / 2),
            cropperT: Math.ceil((SCREEN_WIDTH - SCREEN_WIDTH / IMG_RATIO) / 2),
            cutL: cutL,
            cutT: cutT,
            cutR: cutR,
            cutB: cutB,
            // 图片缩放值
            imageW: IMG_REAL_SHOW_W,
            imageH: IMG_REAL_SHOW_H,
            scaleP: IMG_REAL_SHOW_W / SCREEN_WIDTH,
            qualityWidth: DRAW_IMAGE_W,
            innerAspectRadio: IMG_RATIO
          })
        } else {
          let cutL = Math.ceil((SCREEN_WIDTH * IMG_RATIO - (SCREEN_WIDTH * IMG_RATIO)) /
            2);
          let cutR = cutL;
          let cutT = Math.ceil((SCREEN_WIDTH - INIT_DRAG_POSITION) / 2);
          let cutB = cutT;
          _this.setData({
            cropperW: SCREEN_WIDTH * IMG_RATIO,
            cropperH: SCREEN_WIDTH,
            // 初始化left right
            cropperL: Math.ceil((SCREEN_WIDTH - SCREEN_WIDTH * IMG_RATIO) / 2),
            cropperT: Math.ceil((SCREEN_WIDTH - SCREEN_WIDTH) / 2),

            cutL: cutL,
            cutT: cutT,
            cutR: cutR,
            cutB: cutB,
            // 图片缩放值
            imageW: IMG_REAL_SHOW_W,
            imageH: IMG_REAL_SHOW_H,
            scaleP: IMG_REAL_SHOW_W / SCREEN_WIDTH,
            qualityWidth: DRAW_IMAGE_W,
            innerAspectRadio: IMG_RATIO
          })
        }
        _this.setData({
          isShowImg: true
        })

        console.log('隐藏loading')
        tt.hideLoading()
      },
      fail(res) {
        console.log('加载图片失败：', res)
      }
    })
  },
  // 拖动时候触发的touchStart事件
  contentStartMove(e) {
    PAGE_X = e.touches[0].pageX
    PAGE_Y = e.touches[0].pageY
  },

  // 拖动时候触发的touchMove事件
  contentMoveing(e) {
    var _this = this
    var dragLengthX = (PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO
    var dragLengthY = (PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO
    // 左移
    if (dragLengthX > 0) {
      if (this.data.cutL - dragLengthX < 0) dragLengthX = this.data.cutL
    } else {
      if (this.data.cutR + dragLengthX < 0) dragLengthX = -this.data.cutR
    }

    if (dragLengthY > 0) {
      if (this.data.cutT - dragLengthY < 0) dragLengthY = this.data.cutT
    } else {
      if (this.data.cutB + dragLengthY < 0) dragLengthY = -this.data.cutB
    }
    this.setData({
      cutL: this.data.cutL - dragLengthX,
      cutT: this.data.cutT - dragLengthY,
      cutR: this.data.cutR + dragLengthX,
      cutB: this.data.cutB + dragLengthY
    })

    PAGE_X = e.touches[0].pageX
    PAGE_Y = e.touches[0].pageY
  },

  contentTouchEnd() {

  },

  // 获取图片
  getImageInfo() {
    var _this = this;
    tt.showLoading({
      title: '图片生成中...',
    });

    // 将图片写入画布
    tt.createSelectorQuery()
      .select('#myCanvas') // 在 WXML 中填入的 id
      .fields({ node: true, size: true })
      .exec((res) => {
        console.log("执行绘制：", res);
        // Canvas 对象
        const canvas = res[0].node
        // Canvas 绘制上下文
        const ctx = canvas.getContext('2d')
        var canvasL = (_this.data.cutL / _this.data.cropperW) * IMG_REAL_W;
        var canvasT = (_this.data.cutT / _this.data.cropperH) * IMG_REAL_H;
        var canvasW = ((_this.data.cropperW - _this.data.cutL - _this.data.cutR) / _this.data.cropperW) * IMG_REAL_W;
        var canvasH = ((_this.data.cropperH - _this.data.cutT - _this.data.cutB) / _this.data.cropperH) * IMG_REAL_H;
        
        // 初始化画布大小
        canvas.width = canvasW
        canvas.height = canvasH
        console.log('IMG_REAL_W:' + IMG_REAL_W + ", IMG_REAL_H:" + IMG_REAL_H)
        console.log('canvasL:' + canvasL + ", canvasT:" + canvasT + ', canvasW:' + canvasW + ", canvasH:" + canvasH)
        // 绘制前清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        
        const image = canvas.createImage()
        image.src = _this.data.imageSrc
        image.onload = () => {
          ctx.drawImage(image, canvasL, canvasT, canvasW, canvasH, 0, 0, canvasW, canvasH)
          // 把canvas转换base64数据
          let base64IMG = ctx.canvas.toDataURL()
          // console.log('---toDataURL---', base64IMG)
          const res = tt.getEnvInfoSync();
          let filePath = res.common.USER_DATA_PATH + '/avatar.png'
          console.log('---imgPath_ttfile---', filePath)
          tt.getFileSystemManager().writeFileSync(filePath, tt.base64ToArrayBuffer(base64IMG.replace(/^data:image\/\w+;base64,/, '')))
          tt.hideLoading();
          _this.upGoodsloadImgs(filePath);
        }
      })
  },

  //上传图片 https://v0.api.upyun.com/samxiche/2021119165817629.png
  upGoodsloadImgs(image_srcre) {
    tt.showLoading({
      title: '图片上传中。。。',
      mask: "true"
    });
    var that = this;
    let houzui = image_srcre.substring(image_srcre.lastIndexOf('.'), image_srcre.length)
    console.log("头像后缀：" + houzui);
    let timeStamp = util.getImgOrVideoName()
    let uploadName = 'ava' + timeStamp + houzui;
    var imgUrl = '/' + util.upyun_imgRootName + '/' + that.cuid + '/image/' + uploadName;
    upyun.upload({
      localPath: image_srcre,
      remotePath: imgUrl,
      success: function (res) {
        console.log("图片上传成功：图片链接 = " + imgUrl);
        console.log("返回的上传结果：", res);
        var resImgInfo = JSON.parse(res.data);
        var url = util.upyun_imgHost + resImgInfo.url;
        console.log("图片链接：", url);
        tt.hideLoading();
        let pages = getCurrentPages(); //获取所有页面栈实例列表
        let prevPage = pages[pages.length - 2]; //上一页页面实例
        prevPage.newAvatarUrl = url //保存头像链接到上一个页面
        tt.navigateBack({ //tt.navigateTo跳转的返回，默认1为返回上一级
          delta: 1
        });
      },

      fail: function (errMsg) {
        tt.hideLoading();
        console.log("图片上传失败：", errMsg);
      }
    }, '')

  },


  // 设置大小的时候触发的touchStart事件
  dragStart(e) {
    T_PAGE_X = e.touches[0].pageX
    T_PAGE_Y = e.touches[0].pageY
    CUT_L = this.data.cutL
    CUT_R = this.data.cutR
    CUT_B = this.data.cutB
    CUT_T = this.data.cutT
  },

  // 设置大小的时候触发的touchMove事件
  dragMove(e) {
    var _this = this
    var dragType = e.target.dataset.drag
    switch (dragType) {
      case 'right':
        var dragLength = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO
        if (CUT_R + dragLength < 0) dragLength = -CUT_R
        this.setData({
          cutR: CUT_R + dragLength
        })
        break;
      case 'left':
        var dragLength = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO
        if (CUT_L - dragLength < 0) dragLength = CUT_L
        if ((CUT_L - dragLength) > (this.data.cropperW - this.data.cutR)) dragLength = CUT_L - (this.data.cropperW - this
          .cutR)
        this.setData({
          cutL: CUT_L - dragLength
        })
        break;
      case 'top':
        var dragLength = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO
        if (CUT_T - dragLength < 0) dragLength = CUT_T
        if ((CUT_T - dragLength) > (this.data.cropperH - this.data.cutB)) dragLength = CUT_T - (this.data.cropperH - this
          .cutB)
        this.setData({
          cutT: CUT_T - dragLength
        })
        break;
      case 'bottom':
        var dragLength = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO
        if (CUT_B + dragLength < 0) dragLength = -CUT_B
        this.setData({
          cutB: CUT_B + dragLength
        })
        break;
      case 'rightBottom':
        var dragLengthX = (T_PAGE_X - e.touches[0].pageX) * DRAFG_MOVE_RATIO
        var dragLengthY = (T_PAGE_Y - e.touches[0].pageY) * DRAFG_MOVE_RATIO

        if (CUT_B + dragLengthY < 0) dragLengthY = -CUT_B
        if (CUT_R + dragLengthX < 0) dragLengthX = -CUT_R
        let cutB = CUT_B + dragLengthY;
        let cutR = CUT_R + dragLengthX;

        this.setData({
          cutB: cutB,
          cutR: cutR
        })
        break;
      default:
        break;
    }
  }

})